/*********************
 *      INCLUDES
 *********************/
#include <rtthread.h>
#include <rtdevice.h>
#include "sensor_manager.h"
#include "st_lsm6dsl_sensor_v1.h"
#include <time.h>
#include "step_service.h"  // 添加头文件包含

/*********************
 *      全局步数数据结构
 *********************/
typedef struct {
    uint32_t total_steps;          // 总步数
    uint32_t daily_goal;           // 每日目标步数
    uint32_t calories;             // 消耗卡路里
    float distance;                // 行走距离(公里)
    time_t last_update;            // 最后更新时间
    uint8_t is_active;             // 是否激活计步
    uint32_t last_sensor_steps;    // 传感器上次步数值
    rt_mutex_t lock;               // 数据保护锁
} global_pedometer_data_t;

static global_pedometer_data_t g_pedometer = {
    .total_steps = 0,
    .daily_goal = 10000,
    .calories = 0,
    .distance = 0.0f,
    .last_update = 0,
    .is_active = 1,  // 默认激活
    .last_sensor_steps = 0,
    .lock = RT_NULL
};

static rt_device_t step_sensor_dev = RT_NULL;

/*********************
 *      步数服务API实现
 *********************/

int step_service_get_data(uint32_t *steps, uint32_t *calories, float *distance)
{
    if (g_pedometer.lock == RT_NULL) {
        return -1;
    }
    
    rt_mutex_take(g_pedometer.lock, RT_WAITING_FOREVER);
    
    if (steps) *steps = g_pedometer.total_steps;
    if (calories) *calories = g_pedometer.calories;
    if (distance) *distance = g_pedometer.distance;
    
    rt_mutex_release(g_pedometer.lock);
    return 0;
}

int step_service_set_goal(uint32_t goal)
{
    if (g_pedometer.lock == RT_NULL) {
        return -1;
    }
    
    rt_mutex_take(g_pedometer.lock, RT_WAITING_FOREVER);
    g_pedometer.daily_goal = goal;
    rt_mutex_release(g_pedometer.lock);
    return 0;
}

int step_service_reset(void)
{
    if (g_pedometer.lock == RT_NULL) {
        return -1;
    }
    
    rt_mutex_take(g_pedometer.lock, RT_WAITING_FOREVER);
    g_pedometer.total_steps = 0;
    g_pedometer.calories = 0;
    g_pedometer.distance = 0.0f;
    g_pedometer.last_update = time(NULL);
    
    // 重置传感器基准值
    if (step_sensor_dev != RT_NULL) {
        struct rt_sensor_data data;
        rt_device_read(step_sensor_dev, 0, &data, 1);
        g_pedometer.last_sensor_steps = data.data.step;
    }
    
    rt_mutex_release(g_pedometer.lock);
    return 0;
}

int step_service_set_active(uint8_t active)
{
    if (g_pedometer.lock == RT_NULL) {
        return -1;
    }
    
    rt_mutex_take(g_pedometer.lock, RT_WAITING_FOREVER);
    g_pedometer.is_active = active;
    
    // 如果重新激活，更新基准值
    if (active && step_sensor_dev != RT_NULL) {
        struct rt_sensor_data data;
        rt_device_read(step_sensor_dev, 0, &data, 1);
        g_pedometer.last_sensor_steps = data.data.step;
    }
    
    rt_mutex_release(g_pedometer.lock);
    return 0;
}

int step_service_get_active_status(uint8_t *active)
{
    if (g_pedometer.lock == RT_NULL || active == NULL) {
        return -1;
    }
    
    rt_mutex_take(g_pedometer.lock, RT_WAITING_FOREVER);
    *active = g_pedometer.is_active;
    rt_mutex_release(g_pedometer.lock);
    return 0;
}
/*********************
 *      传感器初始化
 *********************/
static int init_step_sensor(void)
{
    // 初始化硬件IO
    HAL_PIN_Set(PAD_PA40, I2C3_SCL, PIN_PULLUP, 1);
    HAL_PIN_Set(PAD_PA39, I2C3_SDA, PIN_PULLUP, 1);
    
    // 初始化LSM6DSL传感器
    struct rt_sensor_config cfg = {
        .intf.dev_name = "i2c3",
        .intf.user_data = (void *)LSM6DSL_ADDR_DEFAULT,
        .irq_pin.pin = RT_PIN_NONE
    };
    
    rt_hw_lsm6dsl_init("lsm6d", &cfg);
    
    // 查找传感器设备
    step_sensor_dev = rt_device_find("step_lsm");
    if (step_sensor_dev == RT_NULL) {
        rt_kprintf("Can't find step sensor device\n");
        return -1;
    }
    
    // 打开设备
    rt_err_t ret = rt_device_open(step_sensor_dev, RT_DEVICE_FLAG_RDONLY);
    if (ret != RT_EOK) {
        rt_kprintf("Failed to open step sensor: %d\n", ret);
        return -2;
    }
    
    // 配置传感器
    rt_device_control(step_sensor_dev, RT_SENSOR_CTRL_SET_ODR, (void *)26);
    rt_device_control(step_sensor_dev, RT_SENSOR_CTRL_SET_POWER, (void *)RT_SENSOR_POWER_NORMAL);
    
    // 获取初始步数值
    struct rt_sensor_data data;
    if (rt_device_read(step_sensor_dev, 0, &data, 1) == 1) {
        g_pedometer.last_sensor_steps = data.data.step;
    }
    
    rt_kprintf("Step sensor initialized successfully\n");
    return 0;
}

/*********************
 *      步数检测线程
 *********************/
/*********************
 *      步数检测线程
 *********************/
static void step_detection_thread(void *parameter)
{
    uint32_t current_steps = 0;
    uint32_t new_steps = 0;
    
    // 等待系统稳定
    rt_thread_mdelay(2000);
    
    // 初始化传感器
    if (init_step_sensor() != 0) {
        rt_kprintf("Step service: using simulation mode\n");
        // 可以在这里实现模拟模式
    }
    
    while (1) {
        // 只有在激活状态下才进行步数检测
        if (g_pedometer.is_active && step_sensor_dev != RT_NULL) {
            // 读取传感器数据
            struct rt_sensor_data data;
            rt_size_t res = rt_device_read(step_sensor_dev, 0, &data, 1);
            
            if (res == 1) {
                current_steps = data.data.step;
                
                rt_mutex_take(g_pedometer.lock, RT_WAITING_FOREVER);
                
                // 计算新增步数
                if (current_steps >= g_pedometer.last_sensor_steps) {
                    new_steps = current_steps - g_pedometer.last_sensor_steps;
                } else {
                    // 传感器复位处理
                    new_steps = current_steps;
                }
                
                if (new_steps > 0) {
                    g_pedometer.total_steps += new_steps;
                    g_pedometer.last_sensor_steps = current_steps;
                    
                    // 计算衍生数据
                    g_pedometer.calories = (uint32_t)(g_pedometer.total_steps * 0.04f);
                    g_pedometer.distance = g_pedometer.total_steps * 0.0008f;
                    g_pedometer.last_update = time(NULL);
                    
                    rt_kprintf("Step service: +%d steps, Total: %d\n", 
                              new_steps, g_pedometer.total_steps);
                }
                
                rt_mutex_release(g_pedometer.lock);
            }
        } else {
            // 非激活状态下，可以做一些低功耗处理
            rt_thread_mdelay(500); // 减少检测频率以节省功耗
            continue;
        }
        
        rt_thread_mdelay(1000); // 每秒检测一次
    }
}

/*********************
 *      服务初始化
 *********************/
int step_service_init(void)
{
    rt_thread_t thread;
    
    // 如果已经初始化，直接返回
    if (g_pedometer.lock != RT_NULL) {
        return 0;
    }
    
    // 创建互斥锁
    g_pedometer.lock = rt_mutex_create("step_mutex", RT_IPC_FLAG_FIFO);
    if (g_pedometer.lock == RT_NULL) {
        rt_kprintf("Failed to create step service mutex\n");
        return -1;
    }
    
    // 创建步数检测线程
    thread = rt_thread_create("step_service",
                             step_detection_thread,
                             RT_NULL,
                             2048,
                             20,
                             20);
    
    if (thread != RT_NULL) {
        rt_thread_startup(thread);
        rt_kprintf("Step service started\n");
        return 0;
    } else {
        rt_kprintf("Failed to create step service thread\n");
        rt_mutex_delete(g_pedometer.lock);
        g_pedometer.lock = RT_NULL;
        return -2;
    }
}